package org.realogic.btp.dhtmlx.manager;

import java.util.Hashtable;
import java.util.regex.Pattern;

import org.realogic.btp.dhtmlx.dao.DhtmlxGridDefineDAO;
import org.realogic.btp.dhtmlx.define.DhtmlxGridModel;
import org.realogic.btp.resourcefile.KResouceFile;
import org.realogic.btp.resourcefile.KResouceFileReader;
import org.realogic.cfm.KSystemEnvs;

public class DhtmlxGridManager {

	private Hashtable<String, DhtmlxGridModel> cache;
	
	//Grid文件读取器
	private KResouceFileReader resouceFileReader;

	private DhtmlxGridManager() {
		cache = new Hashtable<String, DhtmlxGridModel>(200);
		
		Pattern xmlFileNnamePattern = Pattern.compile("(?:.)*\\.xml");
		resouceFileReader = new KResouceFileReader(KSystemEnvs.getInstance().getDhtmlxGridPath(), xmlFileNnamePattern);
		resouceFileReader.loadAllFirst();
	}

	private static class LazyHolder {
		private static final DhtmlxGridManager INSTANCE = new DhtmlxGridManager();
	}

	public static DhtmlxGridManager getMe() {
		return LazyHolder.INSTANCE;
	}

	public DhtmlxGridModel getDhtmlxGridModel(String theName) {
		DhtmlxGridModel tmpModel = null;
		DhtmlxGridDefineDAO dao = null;
		String tmpName = theName + ".xml";		
		KResouceFile tmpResouceFile = resouceFileReader.getResouceFile(tmpName);
		if (tmpResouceFile == null) {
			throw new IllegalStateException(theName + ".xml 文件不存在...");
		}
		if (tmpResouceFile.isModified()) {
			resouceFileReader.reloadResouceFile(tmpResouceFile);
		} else {
			tmpModel = cache.get(theName);
		}
		if (tmpModel == null) {
			dao = new DhtmlxGridDefineDAO(tmpResouceFile.getResouce().getPath());
			try {
				dao.doParse();
				tmpModel = dao.getModel();
				if (tmpModel == null) {
					throw new IllegalStateException(theName + ".xml 文件不存在...");
				}
				cache.put(theName.trim(), tmpModel);
			} catch (Exception e) {
				throw new IllegalStateException(theName + ".xml 读取时错误...");
			}
		}
		return tmpModel;
	}

	public String toString() {
		return "DhtmlxgridMgr";
	}
}
